<template>
  <div class="container">
    <div class="login-form">
      <h3 class="login-title">智慧园区-登录</h3>
      <el-form ref="loginFormRef" :model="formData" :rules="formRules" label-width="auto" style="max-width: 600px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-checkbox>记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(loginFormRef)">登录</el-button>
          <el-button @click="resetForm(loginFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import { ref } from 'vue';

interface FormData {
  username: string
  password: string
}

const loginFormRef = ref<FormInstance>()

const formData = ref<FormData>({
  username: '',
  password: ''
})

const formRules = ref<FormRules<FormData>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '用户名长度为5-15', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-0]{8}$/, message: '请输入8位密码', trigger: 'blur' }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('校验通过')
    } else {
      console.log('校验未通过!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.login-form {
  width: 500px;
  max-height: 400px;
  box-shadow: 0 0 10px gray;
  margin: 100px auto;
  padding: 50px;

  .login-title {
    text-align: center;
    padding: 20px 0;
  }
}
</style>